//
//  NSString+HWCategory.m
//  OCDome
//
//  Created by 李含文 on 2020/12/1.
//  Copyright © 2020 李含文. All rights reserved.
//

#import "NSString+HWCategory.h"
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (HWCategory)

/// 去除小数点后多余的0
- (NSString *)hw_removeExcessZeros {
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    if ([scan scanFloat:&val] && [scan isAtEnd]) {// 是浮点型
        return (NSString *)@([self doubleValue]);
    } else {
        return self;
    }
}
- (NSString*)hw_removeFloatAllZero {
    NSString * testNumber = self;
    NSString * outNumber = [NSString stringWithFormat:@"%@",@(testNumber.floatValue)];
    //    价格格式化显示
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = kCFNumberFormatterDecimalStyle;
    NSString *formatterString = [formatter stringFromNumber:[NSNumber numberWithFloat:[outNumber doubleValue]]];
    
    NSRange range = [formatterString rangeOfString:@"."]; //现获取要截取的字符串位置
    NSLog(@"--------%lu",(unsigned long)range.length);
    if (range.length > 0) {
        NSString *result = [formatterString substringFromIndex:range.location]; //截取字符串
        if (result.length >= 4) {
            formatterString=[formatterString substringToIndex:formatterString.length-1];
        }
    }
    
    NSLog(@"Formatted number string:%@",formatterString);
    
    NSLog(@"Formatted number string:%@",outNumber);
    //    输出结果为：[1223:403] Formatted number string:123,456,789
    return formatterString;
}

/// 是否是浮点型
- (BOOL)hw_isFloat {
    NSScanner *scan = [NSScanner scannerWithString:self];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}

/// 是否是整形
- (BOOL)hw_isInt {
    NSScanner *scan = [NSScanner scannerWithString:self];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

- (NSString *)hw_md5 {
    if (self.length == 0) return @"";
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}
@end
